package jwt

import (
	"fmt"
	"time"
	"voice_chat_room/internal/config"

	"github.com/golang-jwt/jwt/v5"
)

type Claims struct {
	User `json:"user"`
	jwt.RegisteredClaims
}
type User struct {
	Username string `json:"username"`
	ID       uint   `json:"id"`
}

// 生成JWT
func GenerateToken(username string, id uint) (string, error) {
	expirationTime := time.Now().Add(2 * time.Hour)
	claims := &Claims{
		User: User{
			Username: username,
			ID:       id,
		},
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(expirationTime),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			Issuer:    "myapp",
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString([]byte(config.Config.JWTKey))
}

// 解析并验证JWT
func ParseToken(tokenString string) (*Claims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(config.Config.JWTKey), nil
	})
	if err != nil {
		return nil, err
	}
	if claims, ok := token.Claims.(*Claims); ok && token.Valid {
		return claims, nil
	}
	return nil, fmt.Errorf("invalid token")
}
